<template>
  <div class="app-container">
    <el-form ref="ruleForm" :model="form" :rules="rules" label-width="120px">
      <el-row>
        <el-col :span="12">
          <el-form-item label="考评库名称" prop="kesdName">
            <el-input
              v-model="form.kesdName"
              placeholder="请输入考评库名称，尽量简短"
              maxlength="50"
              show-word-limit
              clearable
            />
          </el-form-item>
        </el-col>
        <el-col>
          <div class="totalButton">
            <span class="totalPoints">总分值:{{ score }}</span>
            <div class="top-right-btn">
              <el-button type="primary" @click="handleSubmit">提交</el-button>
              <el-button type="primary" @click="handleDelete">删除</el-button>
            </div>
          </div>
        </el-col>
        <el-col>
          <el-table
            :data="form.dataList"
            border
            class="borderTable"
            :span-method="objectSpanMethod"
          >
            <el-table-column
              label="一级指标名称"
              align="center"
              prop="index1Id"
            >
              <template #default="scope">
                <el-form-item
                  v-if="scope.row.show"
                  label=""
                  :prop="`dataList.${scope.$index}.index1Name`"
                  label-width="0px"
                  :rules="rules.index1Name"
                >
                  <el-input v-model="scope.row.index1Name" placeholder="请输入">
                    <template #suffix v-if="scope.row.index1Name">
                      <el-icon
                        color="var(--el-color-primary)"
                        @click="handleAdd2(scope.row, scope.$index)"
                        ><Plus
                      /></el-icon>
                    </template>
                  </el-input>
                </el-form-item>
                <span v-if="!scope.row.show">{{ scope.row.index1Name }}</span>
              </template>
            </el-table-column>
            <el-table-column label="分值" align="center" prop="index1Id" width="60">
              <template #default="scope">
                <span>{{ scopeFirst(scope.row, 1) }}</span>
              </template>
            </el-table-column>
            <el-table-column
              label="二级指标名称"
              align="center"
              prop="index2Id"
            >
              <template #default="scope">
                <el-form-item
                  v-if="scope.row.show"
                  label=""
                  :prop="`dataList.${scope.$index}.index2Name`"
                  label-width="0px"
                  :rules="rules.index2Name"
                >
                  <el-input v-model="scope.row.index2Name" placeholder="请输入">
                    <template #suffix v-if="scope.row.index2Name">
                      <el-icon
                        color="var(--el-color-primary)"
                        @click="handleAdd3(scope.row, scope.$index)"
                        ><Plus
                      /></el-icon>
                    </template>
                  </el-input>
                </el-form-item>
                <span v-if="!scope.row.show">{{ scope.row.index2Name }}</span>
              </template>
            </el-table-column>
            <el-table-column label="分值" align="center" prop="index2Id"  width="60"> 
              <template #default="scope">
                <span>{{ scopeFirst(scope.row, 2) }}</span>
              </template>
            </el-table-column>
            <el-table-column
              label="三级指标名称"
              align="center"
              prop="index3Kpi3dId"
            >
              <template #default="scope">
                <el-form-item
                  v-if="scope.row.show"
                  label=""
                  :prop="`dataList.${scope.$index}.index3Kpi3dId`"
                  label-width="0px"
                  :rules="rules.index3Kpi3dId"
                >
                  <el-input
                    v-model="scope.row.index3Kpi3dId"
                    placeholder="请输入"
                    readonly
                    @click="openThree(scope.row, scope.$index)"
                  />
                </el-form-item>
                <span v-if="!scope.row.show">{{
                  scope.row.index3Kpi3dId
                }}</span>
              </template>
            </el-table-column>
            <el-table-column label="分值" align="center" prop="index3Score"  width="90" >
              <template #default="scope">
                <el-form-item
                  v-if="scope.row.show"
                  label=""
                  :prop="`dataList.${scope.$index}.index3Score`"
                  label-width="0px"
                  :rules="rules.index3Score"
                >
                  <el-input
                    v-model="scope.row.index3Score"
                    placeholder="请输入"
                  />
                </el-form-item>
                <span v-if="!scope.row.show">{{ scope.row.index3Score }}</span>
              </template>
            </el-table-column>
            <el-table-column label="系统评分" align="center" prop="isSystem"  width="90">
              <template #default="scope">
                <span v-if="scope.row.isSystem == '0'">否</span>
                <span v-else-if="scope.row.isSystem == '1'">是</span>
                <span v-else></span>
              </template>
            </el-table-column>
            <el-table-column label="指标内容" align="center" prop="remark" show-overflow-tooltip  width="300"/>
            <el-table-column
              label="评分标准"
              align="center"
              prop="index3Standard"
              width="300"
            >
              <template #default="scope">
                <el-form-item v-if="scope.row.show" label="" label-width="0px">
                  <el-input
                    v-model="scope.row.index3Standard"
                    placeholder="请输入"
                  />
                </el-form-item>
                <span v-if="!scope.row.show">{{
                  scope.row.index3Standard
                }}</span>
              </template>
            </el-table-column>
            <el-table-column
              label="操作"
              align="center"
              class-name="small-padding fixed-width"
            >
              <template #default="scope">
                <el-button
                  type="text"
                  v-if="scope.row.index3Id == '' || scope.row.show == true"
                  @click="handleApply(scope.row)"
                  >应用</el-button
                >
                <el-button
                  type="text"
                  v-if="scope.row.show == false"
                  @click="handleUpdate(scope.row)"
                  >修改</el-button
                >
                <el-button
                  type="text"
                  @click="handleDeleteRow(scope.row, score.$index)"
                  >删除</el-button
                >
                <el-button type="text"
                @click="handleChooseData(scope.row)"
                v-if="scope.row.kpIndex3Data.code=='26'&&scope.row.show == false"
                >数据选择</el-button>
              </template>
            </el-table-column>
            <template #append>
              <el-icon
                :size="25"
                color="var(--el-color-primary)"
                style="font-weight: bold; margin: 10px auto"
                @click="handleAdd"
                ><Plus
              /></el-icon>
            </template>
          </el-table>
        </el-col>
      </el-row>
    </el-form>
    <el-dialog title="选择三级指标" v-model="open" width="1200px" append-to-body>
      <ThreeLevelIndexList
        :dialogVisible="open"
        @getSelection="getSelection"
        v-if="open == true"
        ref="threeLevelRef"
        :tableChooseVal="tableChooseVal"
      />
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitFormSelect">确定</el-button>
          <el-button plain @click="open = false">取消</el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog title="数据选择" v-model="dataChooseOpen"  width="800px" append-to-body>
      <el-checkbox :indeterminate="isIndeterminate" v-model="checkAll"  @change="handleCheckAllChange">全部选择</el-checkbox>
      <el-checkbox v-model="checkNo"   @change="handleCheckCancel">全部取消</el-checkbox>
      <div style="margin: 15px 0;"></div>
        <el-checkbox-group v-model="checkedCities" @change="handleCheckedCitiesChange">
          <el-checkbox v-for="(v,i) in cities" :label="v.code" :key="i">{{v.label  }}</el-checkbox>
        </el-checkbox-group>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitDataChoose">保存</el-button>
          <el-button plain @click="closeDataChoose">关闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="addEvaluation">
import {
  isCommit,
  isDeleteIndexById,
  getLatestUnsaveIndex,
  applyIndex,
  deleteKpk,
  getPtgxType,
  updatePtgxTypeNew
} from "@/api/workEvaluation/evaluationStandardSetup/appraisalDatabaseManage.js";
import { dataMethod } from "@/utils/spanTable.js";
import { nextTick, onMounted, toRefs } from "vue";
const router = useRouter();
import ThreeLevelIndexList from "../Components/threeLevelIndexList";
import { v4, v1 } from "uuid";
const { proxy } = getCurrentInstance();
const score = ref(0);
const dataChooseOpen=ref(false)
const chooseVal=ref()
const cityOptions = ref([])
const checkAll = ref(false)
const checkNo = ref(false)
const isIndeterminate = ref(true)
const checkedCities = ref([])
const cities = ref([])
const form = ref({
  kesdName: "",
  id: "",
  dataList: [],
});
const positiveInteger = (rule, value, callback) => {
  const reg = /^[1-9][0-9]*$/;
  if (!value) {
    return callback(new Error("请输入三级分值"));
  } else if (isNaN(value)) {
    return callback(new Error("请输入[0,+∞）的整数"));
  } else if (!reg.test(value)) {
    callback(new Error("请输入[0,+∞）的整数"));
  } else {
    callback();
  }
};
const validatorOne = (rule, value, callback) => {
  if (!value) {
    return callback(new Error("请输入一级指标分值"));
  }
  const reg = /^[+-]?(0|([1-9]\d*))(\.\d+)?$/g;
  if (!reg.test(value)) {
    callback(new Error("只能输入数字"));
  }
  callback();
};
const validatorTwo = (rule, value, callback) => {
  if (!value) {
    return callback(new Error("请输入二级指标分值"));
  }
  const reg = /^[+-]?(0|([1-9]\d*))(\.\d+)?$/g;
  if (!reg.test(value)) {
    callback(new Error("只能输入数字"));
  }
  callback();
};
const rules = ref({
  kesdName: [{ required: true, message: "请输入考评库名称", trigger: "blur" }],
  index1Name: [
    { required: true, message: "请输入一级指标名称", trigger: "blur" },
  ],
  index1Score: [{ require: true, trigger: "blur", validator: validatorOne }],
  index2Name: [
    { required: true, message: "请输入二级指标名称", trigger: "blur" },
  ],
  index2Score: [
    {
      require: true,
      message: "请输入二级指标分数",
      trigger: "blur",
      validator: validatorTwo,
    },
  ],
  index3Kpi3dId: [
    { required: true, message: "请输入三级指标名称", trigger: "blur" },
  ],
  index3Score: [
    { required: true, trigger: "blur", validator: positiveInteger },
  ],
});
const spanObj = ref();
const open = ref(false);
const ind = ref();
const tableChooseVal=ref()
const selectObj = ref({});

watch(
  () => form.value.dataList,
  (val) => {
    spanObj.value = dataMethod(form.value.dataList, [
      "index1Id",
      "index2Id",
      "flag",
    ]);
    if (val) {
      if (val.length > 0) {
        score.value = val.reduce(
          (prev, cur) => prev + Number(cur.index3Score),
          0
        );
      } else {
        score.value = 0;
      }
    }
  },
  { deep: true, immediate: true }
);
// 计算一级指标分值和
const scopeFirst = (row, num) => {
  if (num == 1) {
    if (row.score) {
      return row.score;
    }
    let scoreArr = form.value.dataList.filter(
      (item) => item.index1Id == row.index1Id
    );
    if (scoreArr) {
      return scoreArr.reduce((prev, cur) => prev + Number(cur.index3Score), 0);
    } else {
      return 0;
    }
  } else if (num == 2) {
    if (row.score2) {
      return row.score2;
    }
    let score2Arr = form.value.dataList.filter(
      (item) => item.index2Id == row.index2Id
    );
    if (score2Arr) {
      return score2Arr.reduce((prev, cur) => prev + Number(cur.index3Score), 0);
    } else {
      return 0;
    }
  }
};
// 合并列
function objectSpanMethod({ row, column, rowIndex, columnIndex }) {
  //判断合并列
  const _row = spanObj.value[column.property]
    ? spanObj.value[column.property][rowIndex]
    : 1;
  const _col = _row > 0 ? 1 : 0;
  return {
    rowspan: _row,
    colspan: _col,
  };
}
//失焦事件，使用事件对象拿到dom元素并进行后续样式的修改
const iptBlur = (value, e) => {
  // 输入框失焦之后，背景颜色变为粉色
  e.target.style.background = "pink";
};
// 新增一级
const handleAdd = () => {
  if (!form.value.kesdName) {
    proxy.$modal.msgWarning("请先输入考评库名称！！！");
    return;
  }
  let newUuid = v4();
  newUuid = newUuid.replace(/[-]/g, "");
  let newUuids = v1();
  newUuids = newUuids.replace(/[-]/g, "");
  form.value.dataList.push({
    index1Id: newUuid,
    index1Name: "",
    index1Score: null,
    index2Name: "",
    index2Score: null,
    index2Id: newUuids,
    index3Id: "",
    index3Kpi3dId: "",
    index3Score: null,
    isSystem: "",
    remark: "",
    index3Standard: "",
    kpIndex3Data: {},
    ptgxTypeCodes:'',
    show: true,
  });
};
// 新增二级
const handleAdd2 = (row, index) => {
  let newUuids = v1();
  newUuids = newUuids.replace(/[-]/g, "");
  const num = form.value.dataList.filter(
    (item) => item.index1Id == row.index1Id
  ).length;
  form.value.dataList.splice(index + num, 0, {
    index1Id: row.index1Id,
    index1Name: row.index1Name,
    index1Score: row.index1Score,
    index2Name: "",
    index2Score: null,
    index2Id: newUuids,
    index3Id: "",
    index3Kpi3dId: "",
    index3Score: null,
    isSystem: "",
    remark: "",
    index3Standard: "",
    kpIndex3Data: {},
    ptgxTypeCodes:'',
    show: true,
  });
};

// 新增三级
const handleAdd3 = (row, index) => {
  const num = form.value.dataList.filter(
    (item) => item.index1Id == row.index1Id && item.index2Id == row.index2Id
  ).length;
  form.value.dataList.splice(index + num, 0, {
    index1Id: row.index1Id,
    index1Name: row.index1Name,
    index1Score: row.index1Score,
    index2Name: row.index2Name,
    index2Score: row.index2Score,
    index2Id: row.index2Id,
    index3Id: "",
    index3Kpi3dId: "",
    index3Score: null,
    isSystem: "",
    remark: "",
    index3Standard: "",
    kpIndex3Data: {},
    ptgxTypeCodes:'',
    show: true,
  });
};
// 选择三级
const openThree = (row, index) => {
  tableChooseVal.value=row
  open.value = true;
  ind.value = index;

};
const getSelection = (val) => {
  if(val[0]){
    if(JSON.parse(JSON.stringify(val[0])).code=="26"){
      selectObj.value = JSON.parse(JSON.stringify(val[0]));
      if(tableChooseVal.value.kpIndex3Data.id){
        let arr=[]
        arr=tableChooseVal.value.ptgxTypeCodes.split(',')
        checkedCities.value=arr
      }else{
        checkedCities.value=[]
      }
     
      chooseData()
    }else{
      selectObj.value = JSON.parse(JSON.stringify(val[0]));
    }
  }
};
function chooseData(){
  dataChooseOpen.value=true
  getdataList()
}
// 数据选择
function handleChooseData(val){
  chooseVal.value=val
  let arr=[]
  if(val.ptgxTypeCodes){
    arr=val.ptgxTypeCodes.split(',')
  }
  checkedCities.value=arr
  dataChooseOpen.value=true
  getdataList()
}
// 全选
function handleCheckAllChange(val) {
  checkedCities.value = val ? cityOptions.value : []
  isIndeterminate.value = false
  checkNo.value=false
}
// 取消全选
function handleCheckCancel(){
  checkedCities.value =  []
  isIndeterminate.value = false
  checkAll.value=false
}
// 反选
function handleCheckedCitiesChange(value) {
    let checkedCount = value.length;
    checkAll.value = checkedCount === cities.value.length;
    isIndeterminate.value = checkedCount > 0 && checkedCount < cities.value.length;
}
// 选择三级指标确定
const submitFormSelect = () => {
   let str=checkedCities.value.toString()
  nextTick(() => {
    if (JSON.stringify(selectObj.value) != "{}") {
      let obj = selectObj.value;
      tableChooseVal.value=selectObj.value
      form.value.dataList[ind.value].kpIndex3Data = obj
      form.value.dataList[ind.value].index3Kpi3dId = obj.name;
      form.value.dataList[ind.value].name3Id = obj.id;
      form.value.dataList[ind.value].remark = obj.remark;
      form.value.dataList[ind.value].isSystem = obj.isSystem;
      form.value.dataList[ind.value].ptgxTypeCodes = str;
      open.value = false;
    }
  });
};
// 数据选择保存
const submitDataChoose=()=>{
  if(chooseVal.value!==undefined){
    let str=''
    str=checkedCities.value.toString('')
    chooseVal.value.ptgxTypeCodes=str
    updatePtgxTypeNew({...chooseVal.value}).then(res=>{
      if(res.code==200){
        proxy.$modal.msgSuccess("数据选择修改成功");
        dataChooseOpen.value=false
        getList();
      }
    })
  }else{
    closeDataChoose()
  }
} 
// 关闭数据选择模态框
const closeDataChoose=()=>{
  dataChooseOpen.value = false;
    // checkedCities.value=[]
    checkAll.value=false
    isIndeterminate.value = true;
    checkNo.value = false;
}
// 查询平台数据更新
const getdataList=()=>{
  getPtgxType().then(res=>{
    cities.value=[]
    res.data.forEach((v,i)=>{
      cities.value.push({
        label:v.dictItemName,
        code:v.dictItemCode
      })
      cityOptions.value.push(v.dictItemCode)
    })
  })
}
//应用
const handleApply = (val) => {
  proxy.$refs["ruleForm"].validate((valid) => {
    if (valid) {
      let arr = [];
      form.value.dataList.forEach((v, i) => {
        if (v.index3Id == "" || v.index3Id == null) {
          v.index3Kpi3dId = v.name3Id;
          arr.push(v);
        } else {
          v.index3Kpi3dId = v.kpIndex3Data.id;
          arr.push(v);
        }
      });
      let obj = {
        indexList: arr,
        kesdName: form.value.kesdName,
      };
      applyIndex(obj).then((res) => {
        proxy.$modal.msgSuccess("保存成功");
        getList();
      });
    } else {
      return false;
    }
  });
};
//修改
const handleUpdate = (val) => {
  form.value.dataList.forEach((v,i)=>{
    if(v.index1Id==val.index1Id){
      v.show=true
    }
  })
  // val.show = true;
  // val.index3Kpi3dId = val.kpIndex3Data.name;
  // val.name3Id = val.kpIndex3Data.id;
};
//删除行
const handleDeleteRow = (val) => {
  if (val.index3Id == "" || val.index3Id == null) {
    let index = form.value.dataList.indexOf(val)
    if (index !== -1) {
        form.value.dataList.splice(index, 1)
      }
  } else {
    isDeleteIndexById({ index3Id: val.index3Id }).then((res) => {
      proxy.$modal.msgSuccess("删除成功");
      getList();
    });
  }
};
// 提交按钮
const handleSubmit = () => {
  proxy.$refs["ruleForm"].validate((valid) => {
    if (valid) {
      let isCommitVal=form.value.dataList.every(val=>val.show==false)
      if(isCommitVal==false){
        return  proxy.$modal.msgWarning("有未点击应用的数据,请先点击应用")
      }else{
        form.value.dataList.forEach((v,i)=>{
          v.index3Kpi3dId = v.name3Id;
        })
          isCommit({ name: form.value.kesdName }).then((res) => {
            proxy.$modal.msgSuccess("提交成功");
            router.push({
              path: "/workEvaluation/evaluationStandardSetup/appraisalDatabaseManage",
              // query:{
              //   metaTitle:'考评库管理'
              // }
            });
          });
      }
    } else {
      // proxy.$modal.msgWarning('请输入');
    }
  });
};
// 删除按钮
const handleDelete = () => {
  proxy.$modal
    .confirm("是否确认删除该数据项？")
    .then(function () {
      //   return deleteThreeLevelIndexList({id:id.join(',')});
      deleteKpk().then((res) => {
        if(res.code==200){
          proxy.$modal.msgSuccess("删除成功");
        }
        getList();
      });
    })
    .catch(() => {});
};
const getList = () => {
  getLatestUnsaveIndex().then((res) => {
    if (res.data) {
      res.data.list.forEach((v, i) => {
        v.index3Kpi3dId = v.kpIndex3Data.name;
        v.name3Id = v.kpIndex3Data.id;
        v.isSystem = v.kpIndex3Data.isSystem;
        v.remark = v.kpIndex3Data.remark;
      });
      form.value.dataList = JSON.parse(JSON.stringify(res.data.list));
      form.value.kesdName = res.data.name;
    } else {
      form.value.dataList = [];
      form.value.kesdName = "";
    }
  });
};
onMounted(() => {
  getList();
});
</script>

<style lang="scss" scoped>
:deep(.el-table).borderTable td.el-table__cell {
  border-bottom: 1px solid #ebeef5 !important;
  border-right: 1px solid #ebeef5 !important;
  .cell {
    height: 68px;
    line-height: 68px;
    .el-form-item {
      position: relative;
      top: 18px;
      .el-input__suffix {
        top: 9px;
      }
    }
  }
}
:deep(.el-table__append-wrapper) {
  text-align: center;
}
.totalButton {
  display: flex;
  align-items: center;
  justify-content: space-around;
  margin: 2px 0 20px;
  .totalPoints {
    font-size: 20px;
    color: #f56c6c;
    font-weight: bold;
  }
}
// 设置表格中输入框为边框为0
.ipt {
  border: 0px;
}
</style>
